/*
 * @Author: zhxy
 * @Date: 2021-10-26 16:55:34
 * @LastEditors: zhxy
 * @LastEditTime: 2021-10-27 09:03:22
 * @Description: file content
 */

/*
 * @Description: 工序下拉列表
 * @param : 
 */
$(function(){
	jeDate("#fdate",{
		format:"YYYY-MM-DD",
		isTime:false,
	});
    jeDate("#fdate2",{
		format:"YYYY-MM-DD",
		isTime:false,
	});
	var nowMonth = jeDate.timeStampDate(Math.round(new Date()/1000),'YYYY-MM-DD');
	$('#fdate').val(nowMonth);
	$('#procedureE').selectpicker('destroy');
	$('#procedureP').selectpicker('destroy');
	procedureSelectE();
	procedureSelectP();
	resizeIframeHight();
    formatTitle()
    searchTable();
	//initProcessTable();
});
function procedureSelectE() {
	$.ajax({
		url : pathUrl("bill/findEmp.action"),
		type : "POST",
		dataType : "JSON",
		async : false,
		success : function(ret) {
            $('#procedureE').selectpicker('destroy');
			var val = ret;
			var option = "";
			if(val.length != 0){
				$("#procedureE").empty();
				for (x in val) {
					var str = val[x].fName;
					option += '<option value="' + val[x].id + '">' + str + '</option>';
				}
			}
			$("#procedureE").html(option);
			$('#procedureE').selectpicker('refresh');
		}
	});
}

/*
 * @Description: 工序下拉列表
 * @param : 
 */
function procedureSelectP() {
	$.ajax({
		url : pathUrl("bill/findCustom.action"),
		type : "POST",
		dataType : "JSON",
		async : false,
		success : function(ret) {
            $('#procedureP').selectpicker('destroy');
			var val = ret;
			var option = "";
			if(val.length != 0){
				$("#procedureP").empty();
				for (x in val) {
					var str = val[x].fn;
					option += '<option value="' + val[x].id + '">' + str + '</option>';
				}
			}
			$("#procedureP").html(option);
			$('#procedureP').selectpicker('refresh');
		}
	});
}
$("#query").click(function(){
    searchTable()
    formatTitle()
})
$("#update").click(function(){
    $("#updatePlanModal").modal('show');
})
$("#updatePlanModal").on('hidden.bs.modal',function(){
    $("#planTime").val('');
    $("#fdate2").val('')
    procedureSelectP();
    procedureSelectE()
  })
$("#reset").click(function(){
    $("#planTime").val('');
    $("#fdate2").val('')
    procedureSelectP()
    procedureSelectE()
})
$("#submit").click(function(){
    if(!$("#fdate2").val()){
        toastr.warning('时间不能为空');
        return;
    }
    if(!$("#planTime").val()){
        toastr.warning('工时不能为空');
        return;
    }
    $.ajax({
        url:pathUrl('bill/savePlanWorktime.action'),
        type : "POST",
		dataType : "JSON",
        data:{
            pname:$("#procedureP option:selected").text(),
            ename:$("#procedureE option:selected").text(),
            pdate:$("#fdate2").val(),
            worktime:$("#planTime").val()
        },
        success:function(data){
            if(data.code==='0000'){
                swal_Tips_Short(data.message);
                $("#updatePlanModal").modal('hide');
             }else{
                swal_Tips(data.message);
              }
           

        },
        error:function(){
            swal_Tips_Error();
          }

    })
})

function searchTable(){
    const columns=[[
        {
            title:moment().day(1).format('YYYY-MM-DD')+'--'+moment().day(7).format('YYYY-MM-DD'),
            colspan:2,
            align:'center',
            valign:'middle',

           
        },
    ],[{
            title:'序号',
            field:'index',
            align:'center',
            valign:'middle',
            width:200,
            footerFormatter:function(){
                return '总计'
            }
            
        },
        {
            title:'项目名称',
            field:'pName',
            align:'center',
            valign:'middle',
            width:200
        },
    ]
    ]
    var tableData;
    
    $.ajax({
        url: pathUrl("bill/getPlanWorktime.action"),
        method:'get',
        dataType:'JSON',
        data:{
            date:$("#fdate").val()
        },
        success:function(data){
            /*
            var data=[
                {
                    pName:'test',
                    '五年秋':0,
                    '吴建豪':1
                },
                {
                    pName:'tes2t',
                    '五年秋':0,
                    '吴建豪':1
                }
            ]
            */
            tableData=data;
            let columnCount=0;
            
                for(let key in data[0]){
                    if(key!=='pName'){
                        columnCount++;
                        columns[1].push(
                            {
                                title:key,
                                field:key,
                                align:'center',
                                valign:'middle',
                            },
                        )
                    }
                }
                columns[0].push({
                    title:'项目组成员名单',
                    field:'',
                    align:'center',
                    valign:'middle',
                    colspan:columnCount
                })
                
                columns[0].push({
                    title:'计划投入工时（小时）',
                    field:'itemTotal',
                    align:'center',
                    valign:'middle',
                    rowspan:2,
                    formatter:function(value,row,index,field){
                        var total=0;
                        for(let key in row){
                            if(key!=='pName'&&key!=='index'){
                                total+=Number(row[key])
                            }
                        }
                        return Number(total).toFixed(1);
                    },
                    footerFormatter:function(data,value){
                        var total=0;
                        data.forEach(function(e){
                            for(let key in e){
                                if(key!=='pName'&&key!=='index'){
                                    total+=Number(e[key])
                                }
                            }
                        })
                        return Number(total).toFixed(1);
                    }
                })
                console.log(columns);
                tableData=tableData.map((el,index)=>({
                    ...el,
                    index:index
                }))
                $('#processTable').bootstrapTable('destroy').bootstrapTable({
                    // 请求后台的URL
                    // TODO:补充接口
                    //url: pathUrl("bill/getPlanWorktime.action.action"),
                    data:tableData,
                    //height : $(window).height() - 200,//行高
                    // 请求方式
                    //method: "POST",
                    // 是否使用缓存，默认为true
                    cache: false,
                    // 是否显示分页
                    pagination: true,
                    // 初始化加载第几页
                    pageNumber: 1,
                    // 每页的记录行数
                    pageSize: 20,
                    // 分页方式：client客户端分页，server服务端分页（*）
                    sidePagination: "client",
                    showFooter:true,
                    // 每页记录行数选项
                    pageList: [20, 30, 50, 100],
                    // 传递参数
                    queryParams: function (params) {
                      var data = {};
                     data.date=$('#fdate').val();
                      return data;
                    },
                    // 数据类型
                    dataType: 'JSON',
                    // 每一行的唯一标识，一般为主键列
                    uniqueId: "id",
                    columns
                })
           
     },
        error:function(error){

        }
    });
   
}

function getTimeRange(mydate){
    let d=new Date(mydate);
    let   day=d.getDay();
    let   date=d.getDate();
    if(day==1)
        return d;
    if(day==0)
        return new Date(d.getTime()-6*3600*24);
    else
        return new Date(d.getTime()-(day-1)*3600*24);
   
}


function formatTitle(){
    var date = new Date($('#fdate').val());
    week = date.getDay();
    day = date.getDate();
    if( week == 0){
        　　week = 7;
        }
        var config={
            　　getMonth: date.getMonth()+1,
            　　getYear: date.getFullYear(),
            　　getWeek: Math.ceil((day + 6 - week) / 7),
            }
            console.log($('#fdate').val());
            console.log(config)
     var str=config.getMonth + '月' + ' ' + '第' + config.getWeek + '周全部项目计划工时' ;
     $("#title").html(str);
}

